//
//  NSDictionary+Category.m
//  lc-collect
//
//  Created by mac on 2021/3/3.
//

#import "NSDictionary+Category.h"

@implementation NSDictionary (Category)

/// json字符串转字典
/// @param JSONString string
+ (NSDictionary *)JSONStringTransToDic:(NSString *)JSONString {
    
    if (JSONString == nil) {
        return nil;
    }
    NSData *jsonData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    
    return dic;
}

/// NSDictionary转换成JSON字符串
- (NSString *)dictionaryToJSONString {
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    if (jsonData == nil) {
#ifdef DEBUG
        NSLog(@"fail to get JSON from dictionary: %@, error: %@", self, error);
#endif
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonString;
}

/// 将url参数转换成NSDictionary
/// @param query url 参数
+ (NSDictionary *)dictionaryWithURLQuery:(NSString *)query {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSArray *parameters = [query componentsSeparatedByString:@"&"];
    for(NSString *parameter in parameters) {
        NSArray *contents = [parameter componentsSeparatedByString:@"="];
        if([contents count] == 2) {
            NSString *key = [contents objectAtIndex:0];
            NSString *value = [contents objectAtIndex:1];
//            value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            value = [value stringByRemovingPercentEncoding];
            if (key && value) {
                [dict setObject:value forKey:key];
            }
        }
    }
    return [NSDictionary dictionaryWithDictionary:dict];
}

/// 将NSDictionary转换成url 参数字符串
- (NSString *)dictionaryToUrlQueryString {
    
    NSMutableString *string = [NSMutableString string];
    for (NSString *key in [self allKeys]) {
        if ([string length]) {
            [string appendString:@"&"];
        }
        CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)[[self objectForKey:key] description], NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);
        [string appendFormat:@"%@=%@", key, escaped];
        CFRelease(escaped);
    }
    
    return string;
}

/// 将NSDictionary转换成XML 字符串
- (NSString *)ductionaryToXMLString {
    
    NSString *xmlStr = @"<xml>";
    for (NSString *key in self.allKeys) {
        NSString *value = [self objectForKey:key];
        xmlStr = [xmlStr stringByAppendingString:[NSString stringWithFormat:@"<%@>%@</%@>", key, value, key]];
    }
    xmlStr = [xmlStr stringByAppendingString:@"</xml>"];
    
    return xmlStr;
}

@end
